/*
 * @Descripttion: 
 * @version: 
 * @Author: wangzhilei
 * @Date: 2021-09-14 12:10:04
 * @LastEditors: wangzhilei
 * @LastEditTime: 2021-10-01 02:46:37
 */
#include "../config.h"

/**
 * @func: 
 * @msg: 
 * @param {int} fd
 * @param {char} *vptr
 * @param {ssize_t} maxlen
 * @return {*}
 */
ssize_t readline(int fd, char *vptr, ssize_t maxlen)
{
    ssize_t n, rc;
    char c, *ptr;

    ptr = vptr;
    for (n = 1; n < maxlen; n++)
    {
        if ((rc = read(fd, &c, n)) == 1)
        {
            *ptr++ = c;
            if (c == '\n')
                break;
        }
        else if (rc == 0)
        {
            *ptr = 0;
            return (n - 1);
        }
        else
            return (-1);

        *ptr = 0;
    }
        return (n);
}
int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr;

    if (argc != 2)
    {
        perror("usage:tcpcli");
        exit(1);
    }

    //1.创建套接字
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket error");
        exit(1);
    }
    //2.设置链接服务器地址结体
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT); //将无符号短整型数值转换为网络字节序，即大端模式(big-endian)
    /* 
        h---host 本地主机
        to  就是to 了
        n  ---net 网络的意思

        l 是 unsigned long
        s 是 unsigned short
     */
    //IP地址转换函数，可以在将点分文本的IP地址转换为二进制网络字节序”的IP地址
    //inet_ntop将二进制网络字节序IP地址转换为点分文本的IP地址
    //inet_pton和inet_ntop这2个函数能够处理ipv4和ipv6
    if (inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<0)
    {
        printf("inet_pton error for %s\n",argv[1]);
        exit(1);
    }
    //3.发送链接服务器请求
    if (connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
    {
        perror("connect error");
        exit(1);
    }
    //4.消息处理
    char sendline[MAX_LINE],recvline[MAX_LINE];
    while (fgets(sendline,MAX_LINE,stdin)!=NULL)
    {
        write(sockfd,sendline,strlen(sendline));
        if (readline(sockfd,recvline,MAX_LINE)==0)
        {
            perror("server terminated prematurely");
            exit(1);
        }
        if (fputs(recvline,stdout)==EOF)
        {
            perror("fputs error");
            exit(1);
        }
      
        
    }
    
     //5. 关闭套接字
       close(sockfd);
    return 0;
}
